package com.tencent.hummingbird.portal.controller;

import com.tencent.hummingbird.portal.exception.ServiceException;
import com.tencent.hummingbird.portal.r.R;
import com.tencent.hummingbird.portal.service.IUserService;
import com.tencent.hummingbird.portal.vo.RegisterVO;
import javafx.scene.input.DataFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Controller
@Slf4j
public class SystemController {
    @Value("${hummingbird.resources.path}")
    private File path;
    @Value("${hummingbird.resources.host}")
    private String host;
    @GetMapping("/login.html")
    public ModelAndView login(){
        return new ModelAndView("login");
    }
    @GetMapping("/register.html")
    public ModelAndView  register(){
        return new ModelAndView("register");
    }
    @Autowired
    private IUserService userService;
    @PostMapping("/register")
    public @ResponseBody R registerStudent(@RequestBody @Validated RegisterVO registerVO, BindingResult result){
        log.info("RegisterVO{}",registerVO);
        if(result.hasErrors()){
            return R.unproecsableEntity(result.getFieldError().getDefaultMessage());
        }
        if(!registerVO.getPassword().equals(registerVO.getConfirm())){
            return R.unproecsableEntity("两次密码不一致");
        }

        userService.registerStudent(registerVO);
        return R.created("注册成功");



    }

    @PostMapping("/upload")
    public @ResponseBody R uploadFile(MultipartFile imgFile) throws IOException {
        String dataPath = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDateTime.now());
        File f = new File(path,dataPath);
        if(!f.exists()){
            f.mkdirs();
        }

        String originName = imgFile.getOriginalFilename();
        String ext = originName.substring(originName.lastIndexOf("."));
        String newName = UUID.randomUUID()+ext;

        File path = new File(f,newName);

        imgFile.transferTo(path);
        log.info("host+\"\"+dataPath+\"/\"+newName:{}",host+""+dataPath+"/"+newName);
        return R.ok(host+""+dataPath+"/"+newName);
    }
}
